<!--
 * @Author: SeonHu
 * @Date: 2025-09-16 14:44:19
 * @LastEditors: SeonHu
 * @LastEditTime: 2025-09-23 14:59:33
 * @FilePath: \bg-vben\src\views\dashboard\workbench\components\WorkbenchHeader.vue
 * @Description: 
 * Copyright © 2020-2025 SANQING Corporation, All rights reserved.
-->
<template>
  <div class="lg:flex">
    <Avatar :src="userInfo.Avatar" :size="72" class="!mx-auto !block" />
    <div class="mt-2 flex flex-col justify-center md:ml-6 md:mt-0">
      <h1 class="text-md md:text-lg">
        {{ t('routes.dashboard.workbench.header.welcomeText', [getTimeGreeting, userInfo.NickName]) }}
      </h1>
      <!-- 天气预报插件：https://www.tianqi.com/plugin/ -->
      <iframe
        width="300"
        height="30"
        frameborder="0"
        scrolling="no"
        hspace="0"
        src="https://i.tianqi.com/?c=code&a=getcode&id=34&icon=1"
        v-if="showIframe"
        @error="() => (showIframe = false)"
      ></iframe>
      <span class="text-secondary">
        {{
          t('routes.dashboard.workbench.header.currentOrgLable', [
            userInfo.CurrentDepartment?.Name
              ? `${userInfo.CurrentOrganization?.Name} - ${userInfo.CurrentDepartment?.Name}`
              : userInfo.CurrentOrganization?.Name,
          ])
        }}
        <Button type="link" size="small" @click="handleChangeOrganization">
          {{ t('routes.dashboard.workbench.header.currentOrgChangeText') }}
        </Button>
      </span>
    </div>
    <div class="mt-4 flex flex-1 justify-end md:mt-0">
      <div class="flex flex-col justify-center text-right">
        <!-- <span class="text-secondary"> 待办 </span> -->
        <!-- <span class="text-2xl">2/10</span> -->
      </div>

      <div class="mx-12 flex flex-col justify-center text-right md:mx-16">
        <!-- <span class="text-secondary"> 项目 </span> -->
        <!-- <span class="text-2xl">8</span> -->
      </div>
      <div class="mr-4 flex flex-col justify-center text-right md:mr-10">
        <!-- <span class="text-secondary"> 团队 </span> -->
        <!-- <span class="text-2xl">300</span> -->
      </div>
    </div>
  </div>

  <ChangeOrganizationModal
    @register="registerChangeOrganizationModal"
    :api="getOrganizationSelectTree"
    label-field="Name"
    value-field="Id"
    children-field="Items"
    tree-node-filter-prop="Name"
    :send-title="t('routes.dashboard.workbench.header.currentOrgChangeText')"
    :before-ok-func="handleChangeOrganizationModalOk"
  />
</template>
<script lang="ts" setup>
  import type { OrganizationNode, OrganizationTreeNode } from '@/api/identity/model';

  import { computed, onMounted, ref } from 'vue';

  import { getOrganizationNode, getOrganizationTree } from '@/api/identity';
  import { useModal } from '@/components/AdVxeModal';
  import { SelectOrganizationTreeModal } from '@/components/ViewModal';
  import { OrganizationTypeEnum } from '@/enums/organizationTypeEnum';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useIdentityStore } from '@/store/modules/identity';
  import { Avatar, Button } from 'ant-design-vue';

  /** 组织机构树形选择节点 */
  export interface OrganizationSelectTreeNode extends OrganizationTreeNode {
    /** 是否禁用 */
    disabled: boolean;

    /** 子项集合 */
    Items: OrganizationSelectTreeNode[];
  }

  const ChangeOrganizationModal = SelectOrganizationTreeModal;

  const identityStore = useIdentityStore();
  const { t } = useI18n();
  const { createMessage } = useMessage();

  const getTimeGreeting = computed(() => {
    const currentDate = new Date();
    const currentHours: number = currentDate.getHours();
    let timeGreeting = t('sys.greet.hello');
    if (currentHours >= 0 && currentHours < 12) {
      timeGreeting = t('sys.greet.goodMorning');
    } else if (currentHours >= 12 && currentHours < 18) {
      timeGreeting = t('sys.greet.goodAfternoon');
    } else if (currentHours >= 18 && currentHours < 23) {
      timeGreeting = t('sys.greet.goodNight');
    }
    return timeGreeting;
  });

  const showIframe = ref(true);

  const userInfo = ref(identityStore.getUserInfo);
  onMounted(async () => {
    userInfo.value = identityStore.getUserInfo;
    if (userInfo.value.CurrentOrganization === undefined || userInfo.value.CurrentOrganization === null) {
      const result = await getOrganizationNode();
      if (result.Succeeded) {
        const orgNodes = result.Data;
        if (
          orgNodes !== undefined &&
          orgNodes !== null &&
          orgNodes?.filter((m) => m.EnableLogin === true && m.IsLocked === false)?.length > 0
        ) {
          // TODO：如果存在可登录的组织结构信息，自动弹出更改组织结构页面
          await handleChangeOrganization();
        }
      }
    }
  });

  const [registerChangeOrganizationModal, { openModal: openChangeOrganizationModal }] = useModal();

  /** 获取组织选择树 */
  async function getOrganizationSelectTree(): Promise<OrganizationSelectTreeNode[]> {
    const result = await getOrganizationTree();
    if (result.Succeeded) {
      const orgSelectTreeNodes = result.Data as OrganizationSelectTreeNode[];
      if (orgSelectTreeNodes?.length > 0) {
        orgSelectTreeNodes.forEach((selectTreeNode) => {
          setOrganizationSelectTreeDisabled(selectTreeNode);
        });
      }
      // console.log('orgSelectTreeNodes', orgSelectTreeNodes);
      return orgSelectTreeNodes;
    }
    return [];
  }
  /** 处理组织选择树可选属性 */
  function setOrganizationSelectTreeDisabled(selectTreeNode: OrganizationSelectTreeNode) {
    selectTreeNode.disabled = selectTreeNode.IsLocked;
    if (selectTreeNode.EnableLogin === false && selectTreeNode.Type !== OrganizationTypeEnum.Department) {
      selectTreeNode.disabled = true;
    }

    selectTreeNode.Items.forEach((subItem) => {
      setOrganizationSelectTreeDisabled(subItem);
    });
  }

  /** 处理更改组织 */
  async function handleChangeOrganization() {
    openChangeOrganizationModal(true, {
      organizationId: userInfo.value?.CurrentDepartment
        ? userInfo.value?.CurrentDepartment?.Id
        : userInfo.value?.CurrentOrganization?.Id,
    });
  }

  /** 处理更改组织窗体确认按钮 */
  async function handleChangeOrganizationModalOk(organizationId: string, _data: OrganizationNode) {
    // console.log('handleChangeOrganizationModalOk_organizationId', organizationId);
    // console.log('handleChangeOrganizationModalOk_data', data);
    const currentOrganizationId = userInfo.value?.CurrentDepartment
      ? userInfo.value?.CurrentDepartment?.Id
      : userInfo.value?.CurrentOrganization?.Id;
    try {
      if (organizationId !== undefined && organizationId !== null && organizationId !== '') {
        if (organizationId === currentOrganizationId) {
          createMessage.info(t('routes.dashboard.workbench.header.currentOrgNotChanged'));
          return true;
        }
        const userInfoValue = await identityStore.setOrganization({
          organizationId,
          mode: 'none',
        });
        if (userInfoValue !== undefined && userInfoValue !== null) {
          userInfo.value = userInfoValue;
          createMessage.success(t('routes.dashboard.workbench.header.currentOrgChangeSuccess'));
          return true;
        }
        return false;
      }
      createMessage.error(t('routes.dashboard.workbench.header.orgIdError'));
      return false;
    } catch (error: any) {
      if (error?.message) {
        createMessage.error(error?.message);
      }
      return false;
    }
  }
</script>
